package weeklyreport



import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

import java.text.DateFormat
import java.text.SimpleDateFormat

@Transactional(readOnly = true)
class TaskController {

	static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

	def scaffold = true

	def defaultAction = "index"

	def index(Integer max) {
		params.max = Math.min(max ?: 10, 100)
		if(!params.sort) {
			params.sort = "status"
		}

		if(!params.order) {
			params.order = "desc"
		}
		def tasks
		def count
		if(session.user.admin) {
			tasks = Task.list(params)
			count = Task.count()
		} else {
			tasks = Task.findAllByDeveloper(session.user, params)
			count = Task.countByDeveloper(session.user)
		}
		respond tasks, model:[taskInstanceCount: count]
	}

	def show(Task taskInstance) {
		if(taskInstance.developer.id == session.user.id) {
			respond taskInstance
		} else {
			redirect(action:"index")
		}
	}

	def create() {
		respond new Task(params)
	}

	@Transactional
	def save(Task taskInstance) {
		if (taskInstance == null) {
			notFound()
			return
		}

		if (taskInstance.hasErrors()) {
			println taskInstance.errors
			respond taskInstance.errors, view:'create'
			return
		}

		taskInstance.save flush:true

		request.withFormat {
			form {
				flash.message = message(code: 'default.created.message', args: [
					message(code: 'taskInstance.label', default: 'Task'),
					taskInstance.id
				])
				redirect taskInstance
			}
			'*' { respond taskInstance, [status: CREATED] }
		}
	}

	def edit(Task taskInstance) {
		if(taskInstance.developer.id == session.user.id) {
			respond taskInstance
		} else {
			redirect(action:"index")
		}
	}

	@Transactional
	def update(Task taskInstance) {
		if (taskInstance == null) {
			notFound()
			return
		}

		if (taskInstance.hasErrors()) {
			respond taskInstance.errors, view:'edit'
			return
		}

		taskInstance.save flush:true

		request.withFormat {
			form {
				flash.message = message(code: 'default.updated.message', args: [
					message(code: 'Task.label', default: 'Task'),
					taskInstance.id
				])
				redirect taskInstance
			}
			'*'{ respond taskInstance, [status: OK] }
		}
	}

	@Transactional
	def delete(Task taskInstance) {

		if (taskInstance == null) {
			notFound()
			return
		}

		taskInstance.delete flush:true

		request.withFormat {
			form {
				flash.message = message(code: 'default.deleted.message', args: [
					message(code: 'Task.label', default: 'Task'),
					taskInstance.id
				])
				redirect action:"index", method:"GET"
			}
			'*'{ render status: NO_CONTENT }
		}
	}

	protected void notFound() {
		request.withFormat {
			form {
				flash.message = message(code: 'default.not.found.message', args: [
					message(code: 'taskInstance.label', default: 'Task'),
					params.id
				])
				redirect action: "index", method: "GET"
			}
			'*'{ render status: NOT_FOUND }
		}
	}
}
